#!/usr/bin/env python

import sys, os, re, tempfile, jikes


advice_destination = sys.argv[1]
benchmarks = sys.argv[2:] if len(sys.argv) > 2 else jikes.benchmarks.keys()
print 'Generating advice files into', advice_destination

for app in benchmarks:

  print '===', app, '==='
  advdir = tempfile.mkdtemp()
  bestruntime = ()
  bestrunnr = None
  bestrun = None

  for run in range(5):
    rundir = '%s/run%d' % (advdir, run)
    os.system('mkdir -p %s' % rundir)
    os.environ['HOME'] = rundir

    print 'run', run
    jikes.run_jikes('%s/run.sh' % os.path.abspath(os.path.dirname(__file__)), '>%sout 2>&1' % rundir, app, 4, 1, nruns = 5, advice = rundir)

    output = file('%sout' % rundir).read()
    runtime = re.search('Total time: (.*) ms\n------------------------------ End MMTk Statistics', output)
    if not runtime:
      print '\tinvalid, ignoring'
      print output
      continue

    runtime = runtime.group(1)
    print '\truntime =', float(runtime), 'ms'

    if runtime < bestruntime:
      bestruntime = runtime
      bestrunnr = run
      bestrun = rundir

  print 'copying advice files generated by run', bestrunnr
  os.system('cp %s/* %s' % (bestrun, advice_destination))

  os.system('rm -rf %s' % advdir)
